import { login, logout, getUserInfoByToken, getUserTokenBySsoSession } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    username: '',
    mail: '',
    nickname: '',
    roles: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_MAIL: (state, mail) => {
    state.mail = mail
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickname = nickname
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.Authorization)
          commit('SET_USER_ID', data.userId)
          setToken(data.Authorization)
          resolve()
        })
        .then(() => {
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getUserInfoByToken({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfoByToken(state.userId)
        .then(response => {
          const { data } = response

          if (!data) {
            reject('Verification failed, please Login again.')
          }
          const { userInfo } = data
          const { superuser, username, id } = userInfo

          const roles = []
          if (superuser) {
            roles.push('admin')
          } else {
            roles.push('other')
          }
          data.roles = roles

          commit('SET_ROLES', roles)
          commit('SET_NICKNAME', userInfo.nickname)
          commit('SET_MAIL', userInfo.mail)
          commit('SET_USER_ID', id)
          commit('SET_USERNAME', username)
          commit('SET_AVATAR', userInfo.avatarUrl)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  getUserTokenBySsoSession({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserTokenBySsoSession()
        .then(response => {
          const { data } = response
          if (data.Authorization) {
            commit('SET_TOKEN', data.Authorization)
            commit('SET_USER_ID', data.userId)
            setToken(data.Authorization)
            resolve()
          } else {
            removeToken()
            resetRouter()
            commit('RESET_STATE')
            resolve()
          }
        })
        .then(() => {
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
